<template>
  <div class="box">
    <div class="head">
      <div
        class="back"
        @click="back"
      >
        <van-icon name="arrow-left" />
      </div>
      <van-field
        label
        :left-icon="homeIcon"
        :right-icon="scan_btn"
        input-align="center"
        value="ZegoExpress"
        @click-left-icon="mainMenu"
        @click-right-icon="scanFunc"
        readonly
      />
    </div>

    <!-- <div class="errorBackground">
      <div class="backgroundIcon"></div>
      <div class="err_text">谁拔了我家网线</div>
    </div> -->

    <div class="content">
      <!-- 搜索 -->
      <div
        class="searchFun"
        :class="{animation_s:isScanFun}"
      >
        <div class="searchField">
          <van-field
            v-model="waybill"
            type="number"
            placeholder="input or scan waybaill"
            :left-icon="iconSearch"
            @click-left-icon="search"
          />
        </div>
        <!-- <div class="scan">
          <div class="scanBtn"></div>
        </div> -->
      </div>
      <!-- 地址 信息 -->
      <div class="consignor_content">
        <div class="icon">
          <div class="top"></div>
          <div class="img"></div>
          <div class="end">
            <div class="line"></div>
          </div>
        </div>
        <div class="con_address">
          <van-cell
            @click="editConsignorInfo"
            :title="consignorName"
            :value="consignorInfo"
            :label="consignorPhone"
          />
        </div>
        <div class="book">
          <div
            @click="consInfoBook"
            class="book_icon"
          ></div>
        </div>
      </div>
      <div class="receiver_content">
        <div class="icon">
          <div class="top">
            <div class="line"></div>
          </div>
          <div class="img"></div>
          <div class="end"></div>
        </div>
        <div class="con_address">
          <van-cell
            @click="editReceiverInfo"
            :title="receiverName"
            :value="receiverInfo"
            :label="receiverPhone"
          />
        </div>
        <div class="book">
          <div
            @click="receInfoBook"
            class="book_icon"
          ></div>
        </div>
      </div>
      <!-- 配置 -->
      <div class="configuration">
        <van-action-sheet
          class="deliveryType"
          v-model="deliveryShow"
          :actions="actions"
          @select="onSelect"
        />
        <van-cell
          title="Delivery Type"
          is-link
          :label="deliveryName"
          @click="deliveryShow = true"
        />
        <van-cell
          title="Pick-up Time"
          is-link
          :label="pickTime"
          @click="getPickTime"
        />
        <van-cell
          title="Item Type"
          is-link
          :label="itemType"
          @click="getItemTypes"
        />
        <van-cell title="Pay by">
          <!-- 使用 label 插槽来自定义下方 内容 -->
          <template #label>

            <van-button
              v-for="(item,index) in pay_byArr"
              :key=index
              @click="checkPayer(item)"
              :class="{consignor:  item.type==0,receiver:  item.type==1 }"
              plain
              type="primary"
              size="small"
            >{{item.valueEn}}</van-button>

          </template>
        </van-cell>
      </div>
    </div>
    <div class="bottom">
      <div class="price">
        <p class="text">Estimated Freight:</p>
        <p class="price_li">
          <span>Ks </span>
          <span>{{ price }}</span>
        </p>
      </div>
      <div
        @click="submit"
        class="subBtn"
      >Submit</div>
    </div>

    <pickTimePop
      ref="pickPop"
      :show="isPickTime"
      @closePop="closePop"
      @getPickUpTime="getPickUpTime"
    ></pickTimePop>
    <itemType
      ref="itemType"
      :show="isItemType"
      @closePop="closePop"
      @getItemType="getItemTypeStr"
    ></itemType>
    <mainMenuPop
      :show="isMainMenuPop"
      @closePop="closePop"
    ></mainMenuPop>
    <markPop
      :show="isLogin"
      @closePop="closePop"
    ></markPop>
    <!-- 由于开发期 原型改动 加入首页 考虑后 将首页 做成pop 层 -->
    <mainPop
      v-if="enter"
      @closeMainPop=closeMainPop
    ></mainPop>
  </div>
</template>
<script>
// https://segmentfault.com/a/1190000017114380
import { Toast } from 'vant'
import pickTimePop from '@/components/pop/pickTimePop.vue'
import itemType from '@/components/pop/itemType.vue'
import mainMenuPop from '@/components/pop/mainMenuPop.vue'
import markPop from '@/components/pop/markPop.vue'
import mainPop from '@/components/pop/mainPop.vue'
import LocalStorage from '../../model/localStorage.js'
import { TimeData, validata } from '@/model/timeData.js'
import { ReceivePiece, validatas } from '@/model/receivePiece.js'
import scanMixin from '@/views/home/scanMixin'

import { interfaceUtils } from '@/model/interface.js'
import { getSelectValue, getDeliveryTypeList, toSubmitReceivePiece } from 'api/user.js'
export default {
  components: {
    pickTimePop,
    itemType,
    mainMenuPop,
    markPop,
    mainPop
  },
  mixins: [scanMixin],
  name: 'Main',
  data() {
    return {
      isScanFun: false,
      enter: this.$store.state.app.indexConfig,
      title: 'ZegoExpress',
      homeIcon: require('assets/image/home_icon.png'),
      iconSearch: require('assets/image/icon_search.png'),
      scan_btn: require('assets/image/btn_scan@2x.png'),
      home_btn_address: require('assets/image/home_btn_address.png'),
      home_icon_record: require('assets/image/home_icon_record.png'),

      waybill: '',

      consignorInfo: 'Please fill in the consignor information',
      consignorName: '',
      consignorPhone: '',
      cInfo: {},

      receiverInfo: 'Please fill in the receiver information',
      receiverName: '',
      receiverPhone: '',
      rInfo: {},

      pickTime: '   ',
      itemType: '   ',
      itemTypeSelectId: '',

      payer: true, //默认  由consignor 支付
      payerType: '',

      isPickTime: false,
      isItemType: false,
      deliveryShow: false,
      actions: [{ name: '选项一' }, { name: '选项二' }, { name: '选项三' }],
      selectedDeliveryId: '',
      deliveryName: '',

      isMainMenuPop: false,
      isLogin: false,

      item_typeArr: [],
      pick_up_timeArr: [],
      pay_byArr: []
    }
  },
  created() {
    // window.addEventListener('popstate', this.popstate, false)
    console.log('vuex', this.$store.state.app)
    this.price = this.$store.state.app.price
    this.cInfo = JSON.parse(this.$store.state.app.consignorInfo)
    this.rInfo = JSON.parse(this.$store.state.app.receiverInfo)
    if (this.cInfo.name) {
      this.consignorInfo = this.cInfo.city + '  ' + this.cInfo.address
      this.consignorName = this.cInfo.name
      this.consignorPhone = this.cInfo.phone
    }
    if (this.rInfo.name) {
      this.receiverInfo = this.rInfo.city + '  ' + this.rInfo.address
      this.receiverName = this.rInfo.name
      this.receiverPhone = this.rInfo.phone
    }
  },
  destroyed() {
    // window.removeEventListener('popstate', this.popstate, false)
  },
  mounted() {
    window.history.pushState(null, null, document.URL)
    setTimeout(() => {
      // this.receiverInfo = '为什么为什么为什么为什么为什为'
      // this.consignorInfo = '什么什么为什么么为什么什么为什'
      // this.isPickTime = true
    }, 3000)

    //then 都会执行
    new Promise((resolve, reject) => {
      resolve()
    })
      .then(() => {
        let phone = JSON.parse(this.$store.state.app.userInfo).phone || 'null'
        // let token = this.$store.state.app.token || interfaceUtils.login_token
        let timeValue = new TimeData(phone)
        if (validata(timeValue, TimeData)) {
          let data = timeValue._getData()
          // console.log(data)
          getSelectValue(data)
            .then(res => {
              let result = res.data.result
              // this.item_typeArr
              this.item_typeArr = result.filter(item => {
                return item.key == 'item_type'
              })
              // console.log(this.item_typeArr)
              this.pick_up_timeArr = result.filter(item => {
                return item.key == 'pick_up_time'
              })
              // console.log(this.pick_up_timeArr)

              let payArr = result.filter(item => {
                return item.key == 'pay_by'
              })

              payArr.forEach(item => {
                if (item.valueEn == 'Consignor') {
                  item.type = 0
                }
                if (item.valueEn == 'Receiver') {
                  item.type = 1
                }
              })
              this.pay_byArr = payArr
              // console.log(this.pay_byArr)
            })
            .catch(err => {
              Toast.fail({
                message: err
              })
            })
          // console.log(area)
        }
      })
      .then(() => {
        getDeliveryTypeList()
          .then(res => {
            let newArr = []
            let deliveryTypeList = res.data.deliveryTypeList
            for (let i = 0; i < deliveryTypeList.length; i++) {
              let cell = {
                name: deliveryTypeList[i].deliveryTypeName,
                id: deliveryTypeList[i].deliveryTypeId
              }
              newArr.push(cell)
            }

            this.actions = newArr
          })
          .catch(err => {
            Toast.fail({
              message: err
            })
          })
      })
  },
  computed: {
    price: {
      get: function() {
        return this.$store.getters.price
      },
      set: function() {}
    }
  },
  watch: {},
  methods: {
    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.deliveryShow = false
      // Toast(item.id)
      this.selectedDeliveryId = item.id + ''
      this.deliveryName = item.name
    },
    scanFunc() {
      this.isScanFun = true
      setTimeout(() => {
        this.scan()
      }, 500)
    },
    back() {
      this.$store.dispatch('openIndex')
      this.enter = this.$store.state.app.indexConfig
    },
    closeMainPop(num) {
      this.$store.dispatch('closeIndex')
      console.log(this.$store.state.app.indexConfig)
      this.enter = this.$store.state.app.indexConfig
      /**
       *  num
       *  1  关闭 pop
       *  2  跳转 history
       */
      if (num == '1') {
        // this.enter = false
      } else if (num == '2') {
        // this.enter = false
        this.recordList()
      }
    },
    popstate() {
      //禁止浏览器的前进与后退

      // window.history.forward(-1)
    },
    submit() {
      // console.log(this.itemType)
      let consumerid = LocalStorage.get('token') ? JSON.parse(this.$store.state.app.userInfo).consumerId : 'null'
      // let consignorInfo  "{"provinceId":5,"cityId":10,"zoneId":11,"city":"广东省 广州市 白云区","consumerId":"","doType":"edit"}"
      let shipprovince = JSON.parse(this.$store.state.app.consignorInfo).provinceId || ''
      let shipcity = JSON.parse(this.$store.state.app.consignorInfo).cityId || ''
      let shipzone = JSON.parse(this.$store.state.app.consignorInfo).zoneId || ''

      let receiveprovince = JSON.parse(this.$store.state.app.receiverInfo).provinceId || ''
      let receivecity = JSON.parse(this.$store.state.app.receiverInfo).cityId || ''
      let receivezone = JSON.parse(this.$store.state.app.receiverInfo).zoneId || ''

      let estimatedfreightcharge = this.$store.getters.price + ''
      // console.log('estimatedfreightcharge', estimatedfreightcharge)

      let shipaddress = JSON.parse(this.$store.state.app.consignorInfo).address || ''
      let receiveaddress = JSON.parse(this.$store.state.app.receiverInfo).address || ''

      let shipmember = JSON.parse(this.$store.state.app.consignorInfo).name || ''
      let shipmemberphone = JSON.parse(this.$store.state.app.consignorInfo).phone || ''

      let receivemember = JSON.parse(this.$store.state.app.receiverInfo).name || ''
      let receivememberphone = JSON.parse(this.$store.state.app.receiverInfo).phone || ''
      let phone = LocalStorage.get('token') ? JSON.parse(this.$store.state.app.userInfo).phone : 'null'
      let payType = this.payer ? '0' : '4'

      let receivePiece = new ReceivePiece(
        this.itemType,
        consumerid,
        this.waybill || null,
        shipprovince,
        shipcity,

        shipzone,
        receiveprovince,
        receivecity,
        receivezone,
        estimatedfreightcharge,

        shipaddress,
        receiveaddress,
        shipmember,
        shipmemberphone,
        receivemember,

        receivememberphone,
        this.pickTime,
        this.itemTypeSelectId,
        phone,
        'null',
        payType,
        this.selectedDeliveryId
      )
      console.log("receivePiece",receivePiece)
      if (validatas(receivePiece, ReceivePiece)) {
        let data = receivePiece._getData()
        // console.log('yes')
        toSubmitReceivePiece(data)
          .then(res => {
            // console.log(res)
            //清掉vuex 数据
            this.$store.dispatch('setConsignorInfo', '{}')
            this.$store.dispatch('setReceiverInfo', '{}')
            this.$store.dispatch('setWeight', '0')

            this.$router.push({
              path: '/submitOk'
            })
          })
          .catch(err => {
            Toast.fail({
              message: err
            })
          })
      }
    },
    editReceiverInfo() {
      // console.log()
      // alert('编辑 ReceiverInfo')
      this.$router.push({
        name: 'editItem',
        params: {
          id: 1,
          str: 'ReceiverInfo;' + JSON.stringify(this.rInfo)
        }
      })
    },
    editConsignorInfo() {
      // alert('编辑 ConsignorInfo')
      this.$router.push({
        name: 'editItem',
        params: {
          id: 1,
          str: 'ConsignorInfo;' + JSON.stringify(this.cInfo)
        }
      })
    },
    mainMenu() {
      let token = LocalStorage.get('token')
      // console.log(token)
      if (token == '') {
        this.isLogin = true
      } else {
        this.isMainMenuPop = true
      }
    },
    recordList() {
      // alert('历史列表')
      this.$router.push({
        path: '/myOrder'
      })
    },
    search() {
      alert('搜索订单')
    },

    consInfoBook() {
      // console.log('token', LocalStorage.get('token'))
      if (LocalStorage.get('token')) {
        //   alert('consignor 通讯录')
        this.$router.push({
          // path: '/addressBook'
          name: 'addressBook',
          params: { id: 1, who: 'ConsignorInfo' }
        })

        // https://blog.csdn.net/qq_40851816/article/details/80695124
      } else {
        this.isLogin = true
      }
    },
    receInfoBook() {
      // alert('receInfo通讯录')

      if (LocalStorage.get('token')) {
        //   alert('consignor 通讯录')
        this.$router.push({
          // path: '/addressBook'
          name: 'addressBook',
          params: { id: 2, who: 'ReceiverInfo' }
        })

        // https://blog.csdn.net/qq_40851816/article/details/80695124
      } else {
        this.isLogin = true
      }
    },
    getPickTime() {
      this.$refs.pickPop.getTimeData(JSON.stringify(this.pick_up_timeArr))
      this.isPickTime = true
    },
    getItemTypes() {
      //   alert('666')
      this.$refs.itemType.getItemData(JSON.stringify(this.item_typeArr))
      this.isItemType = true
    },
    selectConsignor() {
      this.payer = true
    },
    selectReceiver() {
      this.payer = false
    },
    closePop() {
      this.isPickTime = false
      this.isItemType = false
      this.isMainMenuPop = false
      this.isLogin = false
    },
    getPickUpTime(data) {
      this.pickTime = data
      this.closePop()
    },
    getItemTypeStr(data, selectId) {
      this.itemType = data
      // console.log(selectId)
      this.itemTypeSelectId = selectId
      this.closePop()
    },
    checkPayer(item) {
      this.pay_byArr.forEach(items => {
        items.type = 1
      })
      item.type = 0
      if (item.valueEn == 'Consignor') {
        this.payer = true
      } else {
        this.payer = false
      }
      console.log(this.payer)
    }
  }
}
</script>
<style lang="scss" scoped>
@import 'assets/css/main/index.scss';
</style>
